package com.yh.user.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;



public class MybatisUtil {
	private static ThreadLocal<SqlSession> threadLoacl= new ThreadLocal<SqlSession>();
	private static SqlSessionFactory sqlSessionFactory;
	
	static{
		try {
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public static SqlSession getSqlSession(){
		SqlSession sqlSession=threadLoacl.get();
		if(sqlSession==null){
			sqlSession=sqlSessionFactory.openSession();
			threadLoacl.set(sqlSession);
		}
		return sqlSession;
	}
	
	public static void closeSqlSession(){
		SqlSession sqlSession=threadLoacl.get();
		if(sqlSession!=null){
			sqlSession.close();
			threadLoacl.remove();
		}
	}
}
